<style lang="less">
@import "../../../styles/table-common.less";
@import "./userManage.less";
.ivu-table-cell {
    padding-left: 4px;
    padding-right: 4px;
}
</style>
<template>
  <div class="search">
    <Card>
      <Row v-show="openSearch" @keydown.enter.native="handleSearch">
        <Form ref="searchForm" :model="searchForm" inline :label-width="70">
          <Form-item label="用户名" prop="real_name">
            <Input
              type="text"
              v-model="searchForm.real_name"
              clearable
              placeholder="请输入用户名"
              style="width: 200px"
            />
          </Form-item>
          <Form-item label="部门" prop="department">
            <Select v-model="searchForm.organization_id" prefix="ios-home" filterable>
              <Option v-for="item in organizationList" :key="item.id" :value="item.id">{{ item.organization_name }}
              </Option>
            </Select>
          </Form-item>
          <Form-item style="margin-left:-35px;" class="br">
            <Button @click="handleSearch" type="primary" icon="ios-search">搜索</Button>
            <Button @click="handleReset">重置</Button>
          </Form-item>
        </Form>
      </Row>
      <Row class="operation">
        <Button @click="add" type="primary" icon="md-person-add">添加用户</Button>
        <Button @click="edit" type="success" icon="md-ribbon">编辑用户</Button>
        <Button @click="pauseUser(true)" type="error" icon="ios-hand-outline">暂停用户</Button>
        <Button @click="pauseUser(false)" type="warning" icon="md-happy">恢复用户</Button>
        <!-- <Button @click="delAll" icon="md-trash">批量删除</Button> -->
        <Dropdown @on-click="handleDropdown">
          <Button>
            更多操作
            <Icon type="md-arrow-dropdown" />
          </Button>
          <DropdownMenu slot="list">
            <DropdownItem name="refresh">刷新</DropdownItem>
            <!-- <DropdownItem name="reset">重置用户密码</DropdownItem> -->
            <DropdownItem name="exportData">导出所选数据</DropdownItem>
            <DropdownItem name="exportAll">导出全部数据</DropdownItem>
            <!-- <DropdownItem name="importData">导入数据(付费)</DropdownItem> -->
          </DropdownMenu>
        </Dropdown>
      </Row>
      <Row v-show="openTip">
        <Alert show-icon>
          已选择
          <span class="select-count">{{selectCount}}</span> 项
          <a class="select-clear" @click="clearSelectAll">清空</a>
        </Alert>
      </Row>
      <Row>
        <Table
          :loading="loading"
          border
          :columns="columns"
          :data="data"
          @on-selection-change="showSelect"
          ref="table"
        ></Table>
        <Table :columns="exportColumns" :data="exportData" ref="exportTable" style="display:none"></Table>
      </Row>
      <Row type="flex" justify="end" class="page">
        <Page
          :current="searchForm.pageNumber"
          :total="total"
          :page-size="searchForm.pageSize"
          @on-change="changePage"
          @on-page-size-change="changePageSize"
          :page-size-opts="[10,20,50]"
          size="small"
          show-total
          show-elevator
          show-sizer
        ></Page>
      </Row>
    </Card>

    <Modal v-model="modalExportAll" title="确认导出" :loading="loadingExport" @on-ok="exportAll">
      <p>您确认要导出全部 {{total}} 条数据？</p>
    </Modal>

    <!-- <check-password ref="checkPass" @on-success="resetPass" /> -->

    <addEdit :data="form" :type="showType" v-model="showUser" @on-submit="getUsers" />
  </div>
</template>

<script>
import { validateMobile } from "@/libs/validate";
import { getOrganization, getUserList, updateUser, getAllRoles } from "@/api/users";
import addEdit from "./addEdit.vue";
import moment from 'moment';
import util from '@/libs/util';
export default {
  name: "user-manage",
  components: {
    addEdit
  },
  data() {
    return {
      height: 510,
      showUser: false,
      showType: "0",
      loading: true,
      openSearch: true,
      openTip: true,
      operationLoading: false,
      loadingExport: true,
      modalExportAll: false,
      selectCount: 0,
      selectList: [],
      organizationList: [],
      searchKey: "",
      searchForm: {
        real_name: "",
        organization_id: 0,
        pageNumber: 1,
        pageSize: 10,
      },
      form: {},
      columns: [
        {
          type: "selection",
          width: 50,
          align: "center",
          fixed: "left"
        },
        {
          type: "index",
          width: 50,
          align: "center",
          fixed: "left"
        },
        {
          title: "手机号(帐号)",
          key: "mobile",
          minWidth: 110,
          align: "center",
          fixed: "left"
        },
        {
          title: "姓名",
          key: "real_name",
          minWidth: 100,
          align: "center",
          fixed: "left",
          render: (h, params) => {
            return h(
              "a",
              {
                on: {
                  click: () => {
                    this.showDetail(params.row);
                  }
                }
              },
              params.row.real_name
            );
          }
        },
        {
          title: "性别",
          key: "sex",
          minWidth: 60,
          align: "center",
          render: (h, params) => {
            let re = "";
            if (params.row.sex == 1) {
              re = "男";
            } else if (params.row.sex == 0) {
              re = "女";
            }
            return h("div", re);
          }
        },
        {
          title: "头像",
          key: "avatar",
          width: 80,
          align: "center",
          render: (h, params) => {
            return h("Avatar", {
              props: {
                src: params.row.avatar
              }
            });
          }
        },
        {
          title: "所属部门",
          key: "organization_name",
          minWidth: 180,
          align: "center",
        },
        {
          title: "职称/岗位",
          key: "jobs",
          minWidth: 110,
          align: "center",
        },
        {
          title: "邮箱",
          key: "e_mail",
          minWidth: 180,
          align: "center",
        },
        {
          title: "用户类型",
          key: "is_superuser",
          align: "center",
          width: 120,
          render: (h, params) => {
            let re = "";
            if (params.row.is_superuser == 1) {
              re = "管理员";
            } else if (params.row.is_superuser == 0) {
              re = "普通用户";
            }
            return h("div", re);
          },
        },
        {
          title: "激活",
          key: "is_stuff",
          align: "center",
          width: 110,
          render: (h, params) => {
            if (params.row.is_stuff == 1) {
              return h("div", [
                h("Badge", {
                  props: {
                    status: "success",
                    text: "已经激活"
                  }
                })
              ]);
            } else {
              return h("div", [
                h("Badge", {
                  props: {
                    status: "error",
                    text: "未激活"
                  }
                })
              ]);
            }
          },
        },
        {
          title: "状态",
          key: "is_delete",
          align: "center",
          width: 100,
          render: (h, params) => {
            if (params.row.is_delete == 1) {
              return h("div", {style: { color: 'red'}}, '帐号停用');
            } else {
              return h("div", {style: { color: 'green'}}, '帐号正常');
            }
          },
        },
        {
          title: "创建时间",
          key: "create_at",
          align: "center",
          width: 180,
          render: (h, params) => {
            let re = moment(params.row.create_at).format('YYYY-MM-DD HH:mm:ss');
            return h("div", re);
          }
        },
      ],
      exportColumns: [
        {
          title: "手机",
          key: "mobile"
        },
        {
          title: "用户名",
          key: "real_name"
        },
        {
          title: "头像",
          key: "avatar"
        },
        {
          title: "所属部门ID",
          key: "organization_id"
        },
        {
          title: "所属部门",
          key: "organization_name"
        },
        {
          title: "职称/岗位",
          key: "jobs"
        },
        {
          title: "邮箱",
          key: "e_mail"
        },
        {
          title: "性别",
          key: "sex"
        },
        {
          title: "删除标志",
          key: "is_delete"
        },
        {
          title: "创建时间",
          key: "create_at"
        }
      ],
      data: [],
      exportData: [],
      total: 0,
    };
  },
  methods: {
    getOrganizations() {
      getOrganization().then(res => {
        if (res.code === 0) {
          this.organizationList.push({id: 0, organization_name: '全部'});
          this.organizationList.push(...res.data.rows);
        }
      })
    },
    getUsers() {
      // 多条件搜索用户列表
      this.loading = true;
      let searchParams = {
        real_name: this.searchForm.real_name,
        organization_id: this.searchForm.organization_id,
        pageNumber: this.searchForm.pageNumber,
        pageSize: this.searchForm.pageSize,
      }
      getUserList(searchParams).then(res => {
        this.loading = false;
        if (res.code == 0) {
          this.data = res.data.raws;
          this.total = res.data.count;
        }
      });
    },
    init() {
      this.getOrganizations();
      this.getUsers();
      this.getRoleList();
    },
    changePage(v) {
      this.searchForm.pageNumber = v;
      this.getUsers();
      this.clearSelectAll();
    },
    changePageSize(v) {
      this.searchForm.pageSize = v;
      this.getUsers();
    },
    handleSearch() {
      this.searchForm.pageNumber = 1;
      this.getUsers();
    },
    handleReset() {
      this.$refs.searchForm.resetFields();
      this.searchForm.real_name = '';
      this.searchForm.pageNumber = 1;
      this.searchForm.pageSize = 10;
      this.searchForm.organization_id = 0;
      // 重新加载数据
      this.getUsers();
      this.selectList = [];
    },
    getRoleList() {
      getAllRoles().then(res => {
        if (res.code === 0) {
          this.roleList = res.data;
        }
      });
    },
    handleDropdown(name) {
      if (name == "refresh") {
        this.getUsers();
      } else if (name == "exportData") {
        if (this.selectCount <= 0) {
          this.$Message.warning("您还未选择要导出的数据");
          return;
        }
        this.$Modal.confirm({
          title: "确认导出",
          content: "您确认要导出所选 " + this.selectCount + " 条数据?",
          onOk: () => {
            this.$refs.exportTable.exportCsv({
              filename: "用户数据"
            });
          }
        });
      } else if (name == "exportAll") {
        this.modalExportAll = true;
      } 
    },
    exportAll() {
      getAllUserList().then(res => {
        this.modalExportAll = false;
        if (res.code === 0) {
          this.exportData = res.data.raws;
          setTimeout(() => {
            this.$refs.exportTable.exportCsv({
              filename: "用户全部数据"
            });
          }, 1000);
        }
      });
    },
    showDetail(v) {
      // 转换null为""
      for (let attr in v) {
        if (v[attr] == null) {
          v[attr] = "";
        }
      }
      let str = JSON.stringify(v);
      let data = JSON.parse(str);
      this.form = data;
      this.showType = "0";
      this.showUser = true;
    },
    add() {
      const hasPermission = util.oneOf('add', this.$route.meta.permTypes);
      if (!hasPermission) {
        this.$Message.error('抱歉，您没有操作权限！');
        return;
      };
      this.showType = "2";
      this.showUser = true;
    },
    edit() {
      if (this.selectList.length !== 1) {
        this.$Message.error('必须且只能选择一条记录进行编辑操作');
        return;
      }
      const hasPermission = util.oneOf('edit', this.$route.meta.permTypes);
      if (!hasPermission) {
        this.$Message.error('抱歉，您没有操作权限！');
        return;
      }; 
      // 转换null为""
      let v = this.selectList[0];
      for (let attr in v) {
        if (v[attr] == null) {
          v[attr] = "";
        }
      }
      let str = JSON.stringify(v);
      let data = JSON.parse(str);
      this.form = data;
      this.showType = "1";
      this.showUser = true;
    },
    pauseUser(value) {
      if (this.selectList.length <= 0) {
        this.$Message.error('至少要选择一条记录进行暂停用户操作');
        return;
      }
      const hasPermission = util.oneOf('delete', this.$route.meta.permTypes);
      if (!hasPermission) {
        this.$Message.error('抱歉，您没有操作权限！');
        return;
      };
      this.$Modal.confirm({
        title: value ? "确认暂停用户" : "确认恢复用户",
        content:
          "您确认要修改所选的 " +
          this.selectCount +
          " 条用户的状态吗?",
        loading: true,
        onOk: () => {
          for(let i=0; i<this.selectList.length; i++) {
            if (value) {
              updateUser({id: this.selectList[i].id, is_delete: 1})
            } else {
              updateUser({id: this.selectList[i].id, is_delete: 0})
            }
            
          }
          this.$Modal.remove();
          this.getUsers();
        }
      });
    },
    showSelect(e) {
      this.exportData = e;
      this.selectList = e;
      this.selectCount = e.length;
    },
    clearSelectAll() {
      this.$refs.table.selectAll(false);
    },
  },
  mounted() {
    // 计算高度
    this.height = Number(document.documentElement.clientHeight - 230);
    this.init();
  }
};
</script>